package com.cqgc.service.impl;

import com.cqgc.mapper.UserMapper;
import com.cqgc.pojo.dto.UserDTO.*;
import com.cqgc.pojo.entity.PageResult;
import com.cqgc.pojo.entity.Result;
import com.cqgc.pojo.entity.RoleUser;
import com.cqgc.pojo.entity.User;
import com.cqgc.pojo.vo.UserLikeVO;
import com.cqgc.service.RoleUserService;
import com.cqgc.service.UserService;
import com.cqgc.utils.ThreadLocalUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceimpl implements UserService {
    private final String FAILED_LOGIN_KEY_PREFIX = "failed_login_attempts:";
    private final String ACCOUNT_LOCK_KEY_PREFIX = "account_lock:";
    @Resource
    RedisTemplate<String, String> redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleUserService roleUserService;
    @Override
    public User login(UserLoginDTO loginDTO) {
        User login = userMapper.login(loginDTO);
        return login;
    }
    /**
     * 根据用户名和手机号查询用户
     *
     * @param userForgetDTO
     * @return
     */
    @Override
    public User findByUsernameAndPhoneNumber(UserForgetDTO userForgetDTO) {
        User byUsernameAndPhoneNumber = userMapper.findByUsernameAndPhoneNumber(userForgetDTO);
        return byUsernameAndPhoneNumber;
    }

    /**
     * 修改密码
     *
     * @param user 用户实体
     * @return
     */

    @Override
    public int update(User user) {
        if (userMapper.update(user) > 0) {
            return 1;
        }
        return 0;
    }
    /**
     * 判断账号是否被锁定
     *
     * @param account
     * @return
     */
    @Override
    public boolean isAccountLocked(String account) {
        String lockKey = ACCOUNT_LOCK_KEY_PREFIX + account;
        Long lockExpireTime = stringRedisTemplate.getExpire(lockKey, TimeUnit.MILLISECONDS);
        System.out.println(lockExpireTime + "aa");
        return lockExpireTime != null && lockExpireTime >= 0;
    }

    /**
     * 登录失败次数+1
     *
     * @param account
     */
    @Override
    public void incrementFailedLoginAttempts(String account) {
        String failedLoginKey = FAILED_LOGIN_KEY_PREFIX + account;
        stringRedisTemplate.opsForValue().increment(failedLoginKey, 1);
        Long currentAttempts = Long.valueOf(stringRedisTemplate.opsForValue().get(failedLoginKey));

        if (currentAttempts >= 5) {
            String lockKey = ACCOUNT_LOCK_KEY_PREFIX + account;
            stringRedisTemplate.opsForValue().set(lockKey, "locked", 5, TimeUnit.MINUTES); // 锁定5分钟
        }
    }

    /**
     * 重置登录失败次数
     *
     * @param account
     */
    @Override
    public void resetFailedLoginAttempts(String account) {
        String failedLoginKey = FAILED_LOGIN_KEY_PREFIX + account;
        stringRedisTemplate.delete(failedLoginKey);
    }

    @Override
    public int findUidByAccount(String account) {
        return userMapper.findUidByAccount(account);
    }

    @Override
    public List<String> getUserRoleInfoMapper(int uid) {
        return userMapper.getUserRoleInfoMapper(uid);
    }

    @Override
    public User findByUser(int uid) {
        return userMapper.findByUser(uid);
    }

    @Override
    public List<String> getUserPermissionInfoMapper(List<String> roles) {
        return userMapper.getUserPermissionInfoMapper(roles);
    }


    @Override
    public PageResult list(UserPageQueryDTO userPageQueryDTO) {
        PageHelper.startPage(userPageQueryDTO.getPageNum(), userPageQueryDTO.getPageSize());
        Page<UserLikeVO> page = userMapper.list(userPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public String findPwdByid(Integer uid) {
        return userMapper.findPwdByid(uid);
    }

    @Override
    public void updatePwd(String newPwd) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer uid = (Integer) map.get("uid");
        userMapper.updatePwd(newPwd, uid);
    }

    @Override
    public int update1(UpdateUserDTO updateUserDTO) {
        User user = new User();
        BeanUtils.copyProperties(updateUserDTO,user);
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer uid = (Integer) map.get("uid");
        user.setUid(uid);
        return userMapper.update1(user);
    }

    @Override
    public UserRegisterDTO findUserByPhone(String phone) {
        return userMapper.findUserByPhone(phone);
    }

    @Override
    @Transactional
    public int register(UserRegisterDTO userRegisterDTO) {
        User user = new User();
        BeanUtils.copyProperties(userRegisterDTO, user);
        user.setAccount(userRegisterDTO.getPhone());
        user.setNickName(userRegisterDTO.getPhone());
        String substring = userRegisterDTO.getPhone().substring(5, 11);
        user.setPassword(substring);
        int i = userMapper.register(user);
        int uid = userMapper.findUidByAccount(user.getAccount());
        if (i>0){
            RoleUser roleUser = new RoleUser();
            roleUser.setRid(userRegisterDTO.getRid());
            roleUser.setUid(uid);
            roleUserService.add(roleUser);
            userMapper.addAvatar(uid);
            return 1;
        }
        return 0;
    }

    @Override
    @Transactional
    public int add(AddUserDTO addUserDTO) {
        User user = new User();
        BeanUtils.copyProperties(addUserDTO,user);
        user.setAccount(addUserDTO.getPhone());
        user.setNickName(addUserDTO.getPhone());
        String s = addUserDTO.getPhone().substring(5,11);
        user.setPassword(s);
        int i = userMapper.addUser(user);
        int uidByAccount = userMapper.findUidByAccount(user.getAccount());
        if (i > 0) {
            RoleUser roleUser = new RoleUser();
            roleUser.setRid(addUserDTO.getRid());
            roleUser.setUid(uidByAccount);
            roleUserService.add(roleUser);
            userMapper.addAvatar(uidByAccount);
            return 1;
        }
        return 0;
    }

    @Override
    public User findAccount(String account) {
        return userMapper.findAccount(account);
    }

    @Override
    public List<User> findUserByRole(int realname) {
        return userMapper.findUserByRole(realname);
    }

    @Override
    public int findRoleByUid(int uid) {
        return userMapper.findRoleByUid(uid);
    }

    @Override
    public void updateAvatar(UpdateUserAvatarDTO updateUserAvatarDTO) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer uid = (Integer) map.get("uid");
        userMapper.updateAvatar(updateUserAvatarDTO.getAvatarUrl(), uid);
    }

    @Override
    public String getImgUrl() {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer uid = (Integer) map.get("uid");
        return userMapper.getImgUrl(uid);
    }

    @Override
    public PageResult findUserByIf(LikeUserDTO likeUserDTO) {
        PageHelper.startPage(likeUserDTO.getPageNum(), likeUserDTO.getPageSize());
        Page<UserLikeVO> page = userMapper.findUserByIf(likeUserDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public int delete(int uid) {
        return userMapper.delete(uid);
    }

    @Override
    public int resetPwd(Integer uid) {
        User user = userMapper.findByUser(uid);
        String newPwd = user.getPhone().substring(5,11);

        return userMapper.resetPwd(newPwd,uid);
    }


}
